﻿using System;
using System.Threading;
using System.Windows.Forms;
using System.Collections.Generic;
//GSM
using GSMMODEM;

using Timer = System.Windows.Forms.Timer;

namespace GSMModemDomo
{
    class FrmMain : Form
    {
        #region 应用程序入口
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new FrmMain());
        }

        #endregion

        #region 窗体设计器

        #region 窗体控件
        private System.Windows.Forms.TextBox _txtWrite;
        private Label _lblRecive;
        private Label _label2;
        private Label _label3;
        private Button _btnClear;
        private ComboBox _cbxPort;
        private ComboBox cbxBote;
        private Button btnUnConnection;
        private Label label4;
        private Label label5;
        private Button btnInit;
        private Button btnConnection;
        private StatusStrip statusStrip1;
        private ToolStripStatusLabel lblState;
        private Button btnReadAll;
        private Button btnRead;
        private NumericUpDown numIdx;
        private Label label1;
        private ToolStripProgressBar toolStripProgressBar1;
        private ToolStripStatusLabel toolStripStatusLabel1;
        private Button btnDelete;
        private TextBox txtRecvice;
        private ComboBox txtPhoneNum;
        private System.Windows.Forms.Button btnSend;

        #endregion

        #region 构造函数
        FrmMain()
        {
            InitializeComponent();
        }
        #endregion

        #region 初始化窗体
        private void InitializeComponent()
        {
            this._txtWrite = new System.Windows.Forms.TextBox();
            this.btnSend = new System.Windows.Forms.Button();
            this._lblRecive = new System.Windows.Forms.Label();
            this._label2 = new System.Windows.Forms.Label();
            this._label3 = new System.Windows.Forms.Label();
            this._btnClear = new System.Windows.Forms.Button();
            this._cbxPort = new System.Windows.Forms.ComboBox();
            this.cbxBote = new System.Windows.Forms.ComboBox();
            this.btnUnConnection = new System.Windows.Forms.Button();
            this.label4 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.btnInit = new System.Windows.Forms.Button();
            this.btnConnection = new System.Windows.Forms.Button();
            this.statusStrip1 = new System.Windows.Forms.StatusStrip();
            this.lblState = new System.Windows.Forms.ToolStripStatusLabel();
            this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
            this.toolStripProgressBar1 = new System.Windows.Forms.ToolStripProgressBar();
            this.btnReadAll = new System.Windows.Forms.Button();
            this.btnRead = new System.Windows.Forms.Button();
            this.numIdx = new System.Windows.Forms.NumericUpDown();
            this.label1 = new System.Windows.Forms.Label();
            this.btnDelete = new System.Windows.Forms.Button();
            this.txtRecvice = new System.Windows.Forms.TextBox();
            this.txtPhoneNum = new System.Windows.Forms.ComboBox();
            this.statusStrip1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.numIdx)).BeginInit();
            this.SuspendLayout();
            // 
            // txtWrite
            // 
            this._txtWrite.Location = new System.Drawing.Point(68, 157);
            this._txtWrite.Multiline = true;
            this._txtWrite.Name = "_txtWrite";
            this._txtWrite.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this._txtWrite.Size = new System.Drawing.Size(323, 97);
            this._txtWrite.TabIndex = 5;
            // 
            // btnSend
            // 
            this.btnSend.Location = new System.Drawing.Point(397, 157);
            this.btnSend.Name = "btnSend";
            this.btnSend.Size = new System.Drawing.Size(119, 99);
            this.btnSend.TabIndex = 6;
            this.btnSend.Text = "&Send";
            this.btnSend.UseVisualStyleBackColor = true;
            this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
            // 
            // lblRecive
            // 
            this._lblRecive.AutoSize = true;
            this._lblRecive.Location = new System.Drawing.Point(9, 26);
            this._lblRecive.Name = "_lblRecive";
            this._lblRecive.Size = new System.Drawing.Size(53, 12);
            this._lblRecive.TabIndex = 13;
            this._lblRecive.Text = "Receive:";
            // 
            // label2
            // 
            this._label2.AutoSize = true;
            this._label2.Location = new System.Drawing.Point(15, 128);
            this._label2.Name = "_label2";
            this._label2.Size = new System.Drawing.Size(47, 12);
            this._label2.TabIndex = 14;
            this._label2.Text = "Number:";
            // 
            // label3
            // 
            this._label3.AutoSize = true;
            this._label3.Location = new System.Drawing.Point(27, 160);
            this._label3.Name = "_label3";
            this._label3.Size = new System.Drawing.Size(35, 12);
            this._label3.TabIndex = 15;
            this._label3.Text = "Send:";
            // 
            // btnClear
            // 
            this._btnClear.Location = new System.Drawing.Point(397, 23);
            this._btnClear.Name = "_btnClear";
            this._btnClear.Size = new System.Drawing.Size(119, 99);
            this._btnClear.TabIndex = 11;
            this._btnClear.Text = "&Clear";
            this._btnClear.UseVisualStyleBackColor = true;
            this._btnClear.Click += new System.EventHandler(this.btnClear_Click);
            // 
            // cbxPort
            // 
            this._cbxPort.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this._cbxPort.FormattingEnabled = true;
            this._cbxPort.Location = new System.Drawing.Point(68, 279);
            this._cbxPort.Name = "_cbxPort";
            this._cbxPort.Size = new System.Drawing.Size(76, 20);
            this._cbxPort.TabIndex = 0;
            // 
            // cbxBote
            // 
            this.cbxBote.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cbxBote.FormattingEnabled = true;
            this.cbxBote.Items.AddRange(new object[] {
            "110",
            "300",
            "1200",
            "2400",
            "4800",
            "9600",
            "19200",
            "38400",
            "57600",
            "115200",
            "230400",
            "460800",
            "921600"});
            this.cbxBote.Location = new System.Drawing.Point(209, 279);
            this.cbxBote.Name = "cbxBote";
            this.cbxBote.Size = new System.Drawing.Size(76, 20);
            this.cbxBote.TabIndex = 1;
            // 
            // btnUnConnection
            // 
            this.btnUnConnection.Location = new System.Drawing.Point(381, 277);
            this.btnUnConnection.Name = "btnUnConnection";
            this.btnUnConnection.Size = new System.Drawing.Size(119, 25);
            this.btnUnConnection.TabIndex = 19;
            this.btnUnConnection.Text = "&UnConnection";
            this.btnUnConnection.UseVisualStyleBackColor = true;
            this.btnUnConnection.Click += new System.EventHandler(this.btnUnConnection_Click);
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(27, 282);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(35, 12);
            this.label4.TabIndex = 17;
            this.label4.Text = "Port:";
            // 
            // label5
            // 
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(150, 283);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(59, 12);
            this.label5.TabIndex = 18;
            this.label5.Text = "BaudRate:";
            // 
            // btnInit
            // 
            this.btnInit.Location = new System.Drawing.Point(397, 129);
            this.btnInit.Name = "btnInit";
            this.btnInit.Size = new System.Drawing.Size(119, 22);
            this.btnInit.TabIndex = 3;
            this.btnInit.Text = "&Initialize";
            this.btnInit.UseVisualStyleBackColor = true;
            this.btnInit.Click += new System.EventHandler(this.btnInit_Click);
            // 
            // btnConnection
            // 
            this.btnConnection.Location = new System.Drawing.Point(297, 277);
            this.btnConnection.Name = "btnConnection";
            this.btnConnection.Size = new System.Drawing.Size(78, 25);
            this.btnConnection.TabIndex = 2;
            this.btnConnection.Text = "&Connection";
            this.btnConnection.UseVisualStyleBackColor = true;
            this.btnConnection.Click += new System.EventHandler(this.btnConnection_Click);
            // 
            // statusStrip1
            // 
            this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.lblState,
            this.toolStripStatusLabel1,
            this.toolStripProgressBar1});
            this.statusStrip1.Location = new System.Drawing.Point(0, 305);
            this.statusStrip1.Name = "statusStrip1";
            this.statusStrip1.Size = new System.Drawing.Size(532, 22);
            this.statusStrip1.SizingGrip = false;
            this.statusStrip1.TabIndex = 20;
            this.statusStrip1.Text = "statusStrip1";
            // 
            // lblState
            // 
            this.lblState.AutoSize = false;
            this.lblState.Name = "lblState";
            this.lblState.Size = new System.Drawing.Size(200, 17);
            this.lblState.Text = "Ready.";
            this.lblState.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
            // 
            // toolStripStatusLabel1
            // 
            this.toolStripStatusLabel1.AutoSize = false;
            this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
            this.toolStripStatusLabel1.Size = new System.Drawing.Size(200, 17);
            // 
            // toolStripProgressBar1
            // 
            this.toolStripProgressBar1.AutoToolTip = true;
            this.toolStripProgressBar1.ForeColor = System.Drawing.Color.IndianRed;
            this.toolStripProgressBar1.Maximum = 4;
            this.toolStripProgressBar1.Name = "toolStripProgressBar1";
            this.toolStripProgressBar1.Size = new System.Drawing.Size(50, 16);
            this.toolStripProgressBar1.ToolTipText = "RSSI";
            this.toolStripProgressBar1.Value = 3;
            // 
            // btnReadAll
            // 
            this.btnReadAll.Location = new System.Drawing.Point(335, 128);
            this.btnReadAll.Name = "btnReadAll";
            this.btnReadAll.Size = new System.Drawing.Size(56, 22);
            this.btnReadAll.TabIndex = 10;
            this.btnReadAll.Text = "Read&All";
            this.btnReadAll.UseVisualStyleBackColor = true;
            this.btnReadAll.Click += new System.EventHandler(this.btnReadAll_Click);
            // 
            // btnRead
            // 
            this.btnRead.Location = new System.Drawing.Point(225, 128);
            this.btnRead.Name = "btnRead";
            this.btnRead.Size = new System.Drawing.Size(49, 22);
            this.btnRead.TabIndex = 8;
            this.btnRead.Text = "&Read";
            this.btnRead.UseVisualStyleBackColor = true;
            this.btnRead.Click += new System.EventHandler(this.btnRead_Click);
            // 
            // numIdx
            // 
            this.numIdx.Location = new System.Drawing.Point(177, 128);
            this.numIdx.Maximum = new decimal(new int[] {
            50,
            0,
            0,
            0});
            this.numIdx.Minimum = new decimal(new int[] {
            1,
            0,
            0,
            0});
            this.numIdx.Name = "numIdx";
            this.numIdx.Size = new System.Drawing.Size(42, 21);
            this.numIdx.TabIndex = 7;
            this.numIdx.Value = new decimal(new int[] {
            1,
            0,
            0,
            0});
            // 
            // label1
            // 
            this.label1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.label1.Location = new System.Drawing.Point(11, 269);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(500, 2);
            this.label1.TabIndex = 16;
            // 
            // btnDelete
            // 
            this.btnDelete.Location = new System.Drawing.Point(280, 128);
            this.btnDelete.Name = "btnDelete";
            this.btnDelete.Size = new System.Drawing.Size(49, 22);
            this.btnDelete.TabIndex = 9;
            this.btnDelete.Text = "&Delete";
            this.btnDelete.UseVisualStyleBackColor = true;
            this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
            // 
            // txtRecvice
            // 
            this.txtRecvice.Location = new System.Drawing.Point(68, 23);
            this.txtRecvice.Multiline = true;
            this.txtRecvice.Name = "txtRecvice";
            this.txtRecvice.ReadOnly = true;
            this.txtRecvice.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.txtRecvice.Size = new System.Drawing.Size(323, 99);
            this.txtRecvice.TabIndex = 12;
            this.txtRecvice.TextChanged += new System.EventHandler(this.txtRecvice_TextChanged);
            // 
            // txtPhoneNum
            // 
            this.txtPhoneNum.FormattingEnabled = true;
            this.txtPhoneNum.Location = new System.Drawing.Point(68, 127);
            this.txtPhoneNum.Name = "txtPhoneNum";
            this.txtPhoneNum.Size = new System.Drawing.Size(103, 20);
            this.txtPhoneNum.TabIndex = 21;
            // 
            // FrmMain
            // 
            this.BackColor = System.Drawing.SystemColors.Control;
            this.ClientSize = new System.Drawing.Size(532, 327);
            this.Controls.Add(this.txtPhoneNum);
            this.Controls.Add(this.txtRecvice);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.numIdx);
            this.Controls.Add(this.btnDelete);
            this.Controls.Add(this.btnRead);
            this.Controls.Add(this.btnReadAll);
            this.Controls.Add(this.statusStrip1);
            this.Controls.Add(this.btnConnection);
            this.Controls.Add(this.btnInit);
            this.Controls.Add(this.btnUnConnection);
            this.Controls.Add(this.cbxBote);
            this.Controls.Add(this._cbxPort);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.label4);
            this.Controls.Add(this._label3);
            this.Controls.Add(this._label2);
            this.Controls.Add(this._lblRecive);
            this.Controls.Add(this._btnClear);
            this.Controls.Add(this.btnSend);
            this.Controls.Add(this._txtWrite);
            this.DoubleBuffered = true;
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.Name = "FrmMain";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "GSMModemDomo";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FrmMain_FormClosing);
            this.Load += new System.EventHandler(this.FrmMain_Load);
            this.statusStrip1.ResumeLayout(false);
            this.statusStrip1.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.numIdx)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        #endregion

        #endregion

        #region 程序变量

        private GsmModem gsmModem = null;
        private System.Windows.Forms.Timer timer;

        #endregion

        #region 基本方法

        private void FrmMain_Load(object sender, EventArgs e)
        {

            this._cbxPort.DataSource = System.IO.Ports.SerialPort.GetPortNames();
            this._cbxPort.SelectedIndex = _cbxPort.Items.Count - 1;
            //
            this.cbxBote.Text = "9600";
            //
            this.btnInit.Enabled = false;
            this.btnSend.Enabled = false;
            this._btnClear.Enabled = false;
            this.btnRead.Enabled = false;
            this.btnDelete.Enabled = false;
            this.btnReadAll.Enabled = false;
            this.btnConnection.Enabled = true;
            this.btnUnConnection.Enabled = false;
            this.toolStripProgressBar1.Visible = false;
        }
        void sms_OnRecieved(object sender, SmsInfo info)
        {
            PlaySound();
            ShowMessage(info);
        }
        private void ShowMessage(SmsInfo info)
        {
            Invoke(new Action<SmsInfo>(x =>
            {
                this.txtRecvice.AppendText("=============== New Message ================\n");
                this.txtRecvice.AppendText(x.Center + "\n");
                this.txtRecvice.AppendText(x.Number + "\n");
                this.txtRecvice.AppendText(x.TimeStamp.ToString() + "\n");
                this.txtRecvice.AppendText(x.Message + "\n");
                this.txtRecvice.AppendText("============================================\n");
                this.txtRecvice.Select(0, 0);
            }), info);
        }
        private static void PlaySound()
        {
            int[] sound = new Int32[] { 7, 8, 9, 8 };
            foreach (int n in sound)
            {
                if (n >= 1 && n <= 9)
                {
                    Console.Beep(n * 500, 500 / 2);
                }
            }
        }
        private void btnUnConnection_Click(object sender, EventArgs e)
        {
            if (gsmModem.IsOpen == true)
            {
                if (gsmModem.Close() == true)
                {
                    this.btnInit.Enabled = false;
                    this.btnSend.Enabled = false;
                    this._btnClear.Enabled = false;
                    this.btnRead.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnReadAll.Enabled = false;
                    this.btnConnection.Enabled = true;
                    this.btnUnConnection.Enabled = false;
                    this.toolStripProgressBar1.Visible = false;

                    this.lblState.Text = "UnConnectioned.";
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("UnConnection Error!", "UnConnection",MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                gsmModem = null;
                this.btnInit.Enabled = false;
                this.btnConnection.Enabled = true;
                this.btnUnConnection.Enabled = false;
            }

        }
        private void SetRssi()
        {
            int rssi = gsmModem.GetRssi();
            if (rssi == 0)
            {
                this.toolStripProgressBar1.Value = 4;
            }
            else if (rssi == 2)
            {
                this.toolStripProgressBar1.Value = 3;
            }
            else if (rssi > 2 && rssi < 30)
            {
                this.toolStripProgressBar1.Value = 2;
            }
            else if (rssi == 31)
            {
                this.toolStripProgressBar1.Value = 1;
            }
            else if (rssi == 99)
            {
                this.toolStripProgressBar1.Value = 0;
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            btnSend.Enabled = false;
            if (String.IsNullOrWhiteSpace(this.txtPhoneNum.Text))
            {
                this.txtRecvice.AppendText("=============== AT Command ================\n");
                this.txtRecvice.AppendText(String.Concat(gsmModem.SendAT(this._txtWrite.Text), "\n"));
                this.txtRecvice.AppendText("============================================\n");
                this.txtRecvice.Select(0, 0);
            }
            else
            {
                Thread thread = new System.Threading.Thread(SendMsg);
                thread.Start();
            }
            btnSend.Enabled = true;
        }

        private void SendMsg()
        {
            Invoke(new Action<FrmMain>(x =>
            {
                string number = x.txtPhoneNum.SelectedValue == null ? x.txtPhoneNum.Text : x.txtPhoneNum.SelectedValue as String;
                if (gsmModem.SendMsg(number, x._txtWrite.Text) == true)
                {
                    System.Windows.Forms.MessageBox.Show("Message Sended.", "Send", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    x._txtWrite.Clear();
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("ERROR !", "Send", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }), this);
        }
        private void btnClear_Click(object sender, EventArgs e)
        {
            this.txtRecvice.Clear();
            this._btnClear.Enabled = false;
        }

        private void btnConnection_Click(object sender, EventArgs e)
        {
            gsmModem = GsmModem.GetInstance(_cbxPort.Text, Convert.ToInt32(cbxBote.Text));
            if (gsmModem != null)
            {
                btnInit.Enabled = true;
                btnConnection.Enabled = false;
                btnUnConnection.Enabled = true;
                this.lblState.Text = "Connectioned.";
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("Connection Error!", "Connection", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void timer_Tick(object sender, EventArgs e)
        {
            if (gsmModem.IsOpen == true)
            {
                SetRssi();
            }
            else
            {
                this.timer.Stop();
                this.toolStripProgressBar1.Visible = false;
            }
        }

        private void btnInit_Click(object sender, EventArgs e)
        {
            if (gsmModem.Init() == true)
            {
                btnInit.Enabled = false;
                btnSend.Enabled = true;
                btnRead.Enabled = true;
                btnDelete.Enabled = true;
                btnReadAll.Enabled = true;
                this.lblState.Text = "Initialize.";

                this.txtPhoneNum.DataSource = gsmModem.GetAllNumber();
                this.txtPhoneNum.DisplayMember = "Name";
                this.txtPhoneNum.ValueMember = "Number";

                #region 监控信号强度
                this.toolStripProgressBar1.Visible = true;
                timer = new Timer();
                timer.Tick += new EventHandler(timer_Tick);
                timer.Interval = 5000;
                timer.Start();
                #endregion
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("Init Error!", "Init", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //this.Close();
            }
            gsmModem.OnRecieved += new GsmModem.OnRecievedHandler(sms_OnRecieved);
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            btnRead.Enabled = false;
            int idx = Convert.ToInt32(this.numIdx.Value);
            SmsInfo info = gsmModem.ReadMsg(idx);
            if (info != null)
            {
                ShowMessage(info);
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("Not Find this Message.", "Find", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            btnRead.Enabled = true;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            DialogResult result = System.Windows.Forms.MessageBox.Show("Are you sure Delete this SMS ?", "Sure ?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            int idx = Convert.ToInt32(this.numIdx.Value);
            if (result == System.Windows.Forms.DialogResult.Yes && gsmModem.DelMsg(idx) == true)
            {
                System.Windows.Forms.MessageBox.Show("This Message Deleted.", "Delete", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if(result == System.Windows.Forms.DialogResult.Yes)
            {
                System.Windows.Forms.MessageBox.Show("Not Find this Message.", "Delete", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void btnReadAll_Click(object sender, EventArgs e)
        {
            btnReadAll.Enabled = false;
            IList<SmsInfo> item = gsmModem.GetAllMsg();
            if (item != null)
            {
                foreach (SmsInfo info in item)
                {
                    ShowMessage(info);
                }
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("Not Find this Message.", "ReadAll", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            btnReadAll.Enabled = true;
        }
        private void txtRecvice_TextChanged(object sender, EventArgs e)
        {
            if (this.txtRecvice.TextLength > 0)
            {
                this._btnClear.Enabled = true;
            }
        }
        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (gsmModem != null && gsmModem.IsOpen == true)
            {
                DialogResult result = System.Windows.Forms.MessageBox.Show("Are you sure UnConnection ?", "Sure ?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    gsmModem.Close();
                    e.Cancel = false;
                }
                else
                {
                    e.Cancel = true;
                }
            }
        }

        #endregion
    }
}
